/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package es.unavarra.mti.iws.logic.properties;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 *
 * @author Asier
 */
public class KProperty {
    private String name;
    private boolean groupable;
    private Field field;
    private Method get, set;
    private Class type;

    public KProperty(String name, boolean groupable, Field field, Class type) {
        this.name = name;
        this.groupable = groupable;
        this.field = field;
       
        this.type = type;
    }

    public KProperty(String name, boolean groupable, Method get, Method set, Class type) {
        this.name = name;
        this.groupable = groupable;
        this.get = get;
        this.set = set;
        this.type = type;
    }

    public boolean isGroupable() {
        return groupable;
    }

    public KProperty setName(String name){
        this.name = name;
        return this;
    }

    public String getName() {
        return name;
    }

    public Class getType() {
        return type;
    }

    public Object getProperty(Object ko){
        try{
            if(field != null){
                return field.get(ko);
            }else{
                if (get != null){
                    return get.invoke(ko, new Object[]{});
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return null;
    }

    public void setProperty(Object ko, Object obj){
        try{
            if(field != null){
                field.set(ko, obj);
            }else{
                if (set != null){
                     set.invoke(ko, new Object[]{obj});
                }
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    public Object getValue(List<HasProperties> objects){
        if(objects == null){
            return null;
        }else if (objects.size() == 1){
            return getProperty(objects.get(0));
        }else{
           int a = 0;
           int b = objects.size()-1;
           while(a < b){
               Object objectA = getProperty(objects.get(a));
               Object objectB = getProperty(objects.get(b));
               if(objectA == null || objectB == null) { return null;}
               if(! objectA.equals(objectB)){ return null;}
               a++;b--;
           }
           return getProperty(objects.get(0));
        }
    }

       public boolean canRead(){
           return field != null || get != null;
       }

        public boolean canWrite(){
           return field != null || set != null;
       }

}
